package com.syezon.wifikey.setting;

import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hodanet.appadvplatclient.ReportAgent;
import com.hodanet.appadvplatclient.ad.AdInfo;
import com.syezon.android.base.utils.AppUtils;
import com.syezon.wifikey.R;
import com.syezon.wifikey.about.AboutActivity;
import com.syezon.wifikey.ad.AdPositionEnum;
import com.syezon.wifikey.ad.AdUtils;
import com.syezon.wifikey.ad.BannerAd;
import com.syezon.wifikey.ad.CommonAdConfig;
import com.syezon.wifikey.ad.CommonAdViewModel;
import com.syezon.wifikey.ad.CommonNewAdCallBack;
import com.syezon.wifikey.ad.ConfigService;
import com.syezon.wifikey.ad.FullVideoAd;
import com.syezon.wifikey.ad.VideoAd;
import com.syezon.wifikey.analysis.AnalysisHelper;
import com.syezon.wifikey.base.BaseFragment;
import com.syezon.wifikey.channel.ChannelConfig;
import com.syezon.wifikey.imageloader.ImageLoader;
import com.syezon.wifikey.utils.MarketUtils;
import com.syezon.wifikey.utils.StatusBarUtil;
import com.syezon.wifikey.view.verticalbannerview.VerticalBannerView;
import com.syezon.wifikey.wifi.adapter.VerticalBannerAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class MeFragment extends BaseFragment implements FullVideoAd.OnFullVideoAdLoadFailedListener, CommonNewAdCallBack {

    private static final String TAG = MeFragment.class.getSimpleName();

    @BindView(R.id.tv_gift_text)
    TextView mTvGiftText;

    @BindView(R.id.ll_top)
    LinearLayout mLlTop;
    @BindView(R.id.rl_grade)
    RelativeLayout mRlGrade;
    @BindView(R.id.fl_gdt_ad_container)
    FrameLayout mFlGdtContainer;

    @BindView(R.id.ll_gift)
    LinearLayout mLlGift;


    @BindView(R.id.verticalBanner)
    VerticalBannerView mVerticalBannerView;
    @BindView(R.id.iv_list_ad1_icon)
    ImageView ivListAd1Icon;
    @BindView(R.id.tv_list_ad1)
    TextView tvListAd1;
    @BindView(R.id.iv_list_ad1_btn)
    ImageView ivListAd1Btn;
    @BindView(R.id.cl_list_ad1)
    ConstraintLayout clListAd1;
    @BindView(R.id.iv_list_ad2_icon)
    ImageView ivListAd2Icon;
    @BindView(R.id.tv_list_ad2)
    TextView tvListAd2;
    @BindView(R.id.tv_list_ad2_btn)
    TextView tvListAd2Btn;
    @BindView(R.id.cl_list_ad2)
    ConstraintLayout clListAd2;
    Unbinder unbinder;
    private List<AdInfo> mBannerData = new ArrayList<>();
    /**
     * 顶部banner
     */
    private VerticalBannerAdapter mBannerAdapter;
    private CommonAdViewModel mBannerAdViewModel;

    @BindView(R.id.iv_float_ad)
    ImageView mIvFloatWifiTop;
    @BindView(R.id.iv_banner)
    ImageView ivBanner;
    private AdInfo nextAdSourceTop;
    /**
     * 顶部悬浮窗
     */
    private CommonAdConfig mTopAdConfig;
    private CommonAdViewModel mTopFloatAdViewModel;

    /**
     * 底部banner
     */
    private CommonAdConfig mBannerBtmAdConfig;
    private CommonAdViewModel mBannerBtmViewModel;
    private BannerAd mBannerAd;
    private FullVideoAd mFullVideoAd;
    private VideoAd videoAd;
    private boolean isLoadedBanner = false;

    /**
     * vip视频
     */
    private CommonAdConfig mVipConfig;
    private CommonAdViewModel mVipViewModel;

    /**
     * 列表广告位1
     */
    private CommonAdConfig mListAD1Config;
    private CommonAdViewModel mListAD1ViewModel;

    /**
     * 列表广告位2
     */
    private CommonAdConfig mListAD2Config;
    private CommonAdViewModel mListAD2ViewModel;
    private AnimationSet animationSet;
    private static final int ANIMATION = 11;
    Handler mHandlerAn = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ANIMATION:
                    try {
                        if (mIvFloatWifiTop.isShown() && animationSet != null) {
                            mIvFloatWifiTop.clearAnimation();
                            mIvFloatWifiTop.startAnimation(animationSet);
                        }
                        mHandlerAn.sendEmptyMessageDelayed(ANIMATION, 7000);
                    }catch (Exception e){

                    }
                    break;
            }
        }
    };
    public MeFragment() {
    }

    public static MeFragment newInstance() {
        MeFragment fragment = new MeFragment();
        return fragment;
    }

    @Override
    protected void initViewsAndEvents() {
        StatusBarUtil.setPaddingSmart(getContext(), mLlTop);
        if (MarketUtils.canJump(mContext)) {
            mRlGrade.setVisibility(View.VISIBLE);
        }
        initAnimation();
        mBannerAdapter = new VerticalBannerAdapter(mContext, mBannerData);
        mBannerAdapter.setOnBannerClickListener(new VerticalBannerAdapter.OnBannerClickListener() {
            @Override
            public void onBannerClick(AdInfo adInfo) {
                if (adInfo.getType() == AdInfo.AD_TYPE_CSJ_FULL_VIDEO) {
                    loadFullVideoAd(adInfo);
                    ReportAgent.reportAdvClick(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                } else if (adInfo.getType() == AdInfo.AD_TYPE_GUANG_DIAN_TONG || adInfo.getType() == AdInfo.AD_TYPE_CHUAN_SHAN_JIA) {
                    videoAd = new VideoAd(getActivity());
                    videoAd.loadVideoAd(adInfo);
                    ReportAgent.reportAdvClick(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                } else {
                    AdUtils.adClicked(getContext(), adInfo, AdPositionEnum.BANNER_ME_TOP);
                }
            }
        });
        mVerticalBannerView.setAdapter(mBannerAdapter);

        getAd();
        updateGiftState();
    }

    private void updateGiftState() {
        boolean showCSJAd = ConfigService.getInstance().isShowCSJAd();
        if (showCSJAd) {
            mLlGift.setVisibility(View.VISIBLE);
        } else {
            mLlGift.setVisibility(View.GONE);
        }
        if (!BookGiftHelper.isLock()) {
            mTvGiftText.setSelected(true);
            mTvGiftText.setText("已解锁,进入福利中心");
        } else {
            mTvGiftText.setSelected(false);
            mTvGiftText.setText("解锁福利");
        }
    }
    private void initAnimation() {
        //由小变大
        Animation scaleAnim = new ScaleAnimation(0.8f, 1.1f, 0.8f, 1.1f);
        //从左向右
        Animation rotateAnim = new RotateAnimation(-10f, 10f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

        scaleAnim.setDuration(1000);
        rotateAnim.setDuration(1000 / 10);
        rotateAnim.setRepeatMode(Animation.REVERSE);
        rotateAnim.setRepeatCount(30);

        animationSet = new AnimationSet(false);
        animationSet.addAnimation(scaleAnim);
        animationSet.addAnimation(rotateAnim);
    }
    private void getAd() {
        mTopAdConfig = new CommonAdConfig(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.FLOAT_HOME_TOP);
        mTopFloatAdViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.FLOAT_HOME_TOP.getUmengEventId(), CommonAdViewModel.class);
        mTopFloatAdViewModel.setAdPositionEnum(AdPositionEnum.FLOAT_HOME_TOP);
        mTopFloatAdViewModel.getAdLiveData().observe(this, adInfos -> {
            mTopAdConfig.setAdList(adInfos);
            showTopFloatAd();
            mHandlerAn.sendEmptyMessageDelayed(ANIMATION, 5000);
        });

        mBannerAdViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.BANNER_ME_TOP.getUmengEventId(), CommonAdViewModel.class);
        mBannerAdViewModel.setAdPositionEnum(AdPositionEnum.BANNER_ME_TOP);
        mBannerAdViewModel.getAdLiveData().observe(this, adInfos -> {
            mBannerData.clear();
            if (adInfos != null && adInfos.size() > 0) {
                mBannerData.addAll(adInfos);
            }
            if (!mBannerData.isEmpty()) {
                mVerticalBannerView.setVisibility(View.VISIBLE);
            } else {
                mVerticalBannerView.setVisibility(View.GONE);
            }
            mBannerAdapter.notifyDataChanged();
        });
//        if (ConfigService.getInstance().isShowGDTAd()) {
//            mBannerAd = new GDTBannerAd(getActivity(), mFlGdtContainer, "3031313282239741");
//            mBannerAd.loadAd();
//        }
        mBannerBtmAdConfig = new CommonAdConfig(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.BOX_AD_2);
        mBannerAd = new BannerAd(getActivity(), mFlGdtContainer);
        mBannerAd.setCommonNewAdCallBack(this);
        mBannerBtmViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.BOX_AD_2.getUmengEventId(), CommonAdViewModel.class);
        mBannerBtmViewModel.setAdPositionEnum(AdPositionEnum.BOX_AD_2);
        mBannerBtmViewModel.getAdLiveData().observe(this, adInfos -> {
            mBannerBtmAdConfig.setAdList(adInfos);
            isLoadedBanner = true;
            loadBanner();
        });
        mVipConfig = new CommonAdConfig(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.VIP_VIDEO);
        mVipViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.VIP_VIDEO.getUmengEventId(), CommonAdViewModel.class);
        mVipViewModel.setAdPositionEnum(AdPositionEnum.VIP_VIDEO);
        mVipViewModel.getAdLiveData().observe(this, adInfos -> {
            mVipConfig.setAdList(adInfos);
        });

        mListAD1Config = new CommonAdConfig(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.LIST_AD1);
        mListAD1ViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.LIST_AD1.getUmengEventId(), CommonAdViewModel.class);
        mListAD1ViewModel.setAdPositionEnum(AdPositionEnum.LIST_AD1);
        mListAD1ViewModel.getAdLiveData().observe(this, adInfos -> {
            mListAD1Config.setAdList(adInfos);
            showListAd1();
        });
        mListAD2Config = new CommonAdConfig(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.LIST_AD2);
        mListAD2ViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.LIST_AD2.getUmengEventId(), CommonAdViewModel.class);
        mListAD2ViewModel.setAdPositionEnum(AdPositionEnum.LIST_AD2);
        mListAD2ViewModel.getAdLiveData().observe(this, adInfos -> {
            mListAD2Config.setAdList(adInfos);
            showListAd2();
        });
    }

    private void showListAd1() {
        AdInfo nextAdSource = mListAD1Config.getNextAdSource();
        if (nextAdSource != null) {
            clListAd1.setVisibility(View.VISIBLE);
            ImageLoader.getInstance().displayImage(getContext(), nextAdSource.getIcon(), ivListAd1Btn);
            ImageLoader.getInstance().displayImage(getContext(), nextAdSource.getPic(), ivListAd1Icon);
            tvListAd1.setText(nextAdSource.getName());
            //AnalysisHelper.onAdEvent(AdPositionEnum.FLOAT_HOME_TOP, AnalysisHelper.EVENT_EXT_SHOW, nextAdSource.getId() + "");
            ReportAgent.reportAdvExtShow(nextAdSource, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
            clListAd1.setOnClickListener(v -> handleFloatAdClick(nextAdSource, AdPositionEnum.LIST_AD1));
            mListAD1Config.saveLastShowAd(nextAdSource);
        } else {
            clListAd1.setVisibility(View.GONE);
        }
    }
    private void showListAd2() {
        AdInfo nextAdSource = mListAD2Config.getNextAdSource();
        if (nextAdSource != null) {
            clListAd2.setVisibility(View.VISIBLE);
            ImageLoader.getInstance().displayImage(getContext(), nextAdSource.getPic(), ivListAd2Icon);
            tvListAd2Btn.setText(nextAdSource.getButton());
            tvListAd2.setText(nextAdSource.getName());
            //AnalysisHelper.onAdEvent(AdPositionEnum.FLOAT_HOME_TOP, AnalysisHelper.EVENT_EXT_SHOW, nextAdSource.getId() + "");
            ReportAgent.reportAdvExtShow(nextAdSource, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
            clListAd2.setOnClickListener(v -> handleFloatAdClick(nextAdSource, AdPositionEnum.LIST_AD1));
            mListAD2Config.saveLastShowAd(nextAdSource);
        } else {
            clListAd2.setVisibility(View.GONE);
        }
    }
    @Override
    protected int getContentViewLayoutID() {
        return R.layout.app_setting_fragment;
    }

    @OnClick({R.id.ll_gift, R.id.rl_about, R.id.rl_feedback, R.id.rl_grade})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_gift:
                BookGiftHelper.getGift(getActivity(), new BookGiftHelper.GetGiftCallBack() {
                    @Override
                    public void getGift() {
                        AdInfo vipAdInfo = mVipConfig.getNextAdSource();
                        if (vipAdInfo.getType() == AdInfo.AD_TYPE_CSJ_FULL_VIDEO) {
                            loadFullVideoAd(vipAdInfo);
                            //ReportAgent.reportAdvClick(vipAdInfo, ChannelConfig.getChannel(), com.blankj.utilcode.util.AppUtils.getAppVersionCode());
                        } else if (vipAdInfo.getType() == AdInfo.AD_TYPE_GUANG_DIAN_TONG || vipAdInfo.getType() == AdInfo.AD_TYPE_CHUAN_SHAN_JIA) {
                            videoAd = new VideoAd(getActivity());
//            videoAd.setOnVideoAdLoadFailedListener(this);
                            videoAd.loadVideoAd(vipAdInfo);
                            //ReportAgent.reportAdvClick(vipAdInfo, ChannelConfig.getChannel(), com.blankj.utilcode.util.AppUtils.getAppVersionCode());
                        } else {
                            AdUtils.adClicked(getContext(), vipAdInfo, AdPositionEnum.VIP_VIDEO);
                        }
                    }
                });
                break;
            case R.id.rl_about:
                readyGo(AboutActivity.class);
                break;
            case R.id.rl_feedback:
                FeedBackActivity.feedBack(mContext);
                break;
            case R.id.rl_grade:
                MarketUtils.launchAppDetail2(mContext);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBannerAd != null) {
            mBannerAd.destroy();
        }
    }

    public void showTopFloatAd() {
        nextAdSourceTop = mTopAdConfig.getNextAdSource();
        if (nextAdSourceTop != null) {
            mIvFloatWifiTop.setVisibility(View.VISIBLE);
            ImageLoader.getInstance().displayImage(getContext(), nextAdSourceTop.getPic(), mIvFloatWifiTop);
            AnalysisHelper.onAdEvent(AdPositionEnum.FLOAT_HOME_TOP, AnalysisHelper.EVENT_EXT_SHOW, nextAdSourceTop.getId() + "");
            ReportAgent.reportAdvExtShow(nextAdSourceTop, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
            mIvFloatWifiTop.setOnClickListener(v -> handleFloatAdClick(nextAdSourceTop, AdPositionEnum.FLOAT_HOME_TOP));
            mTopAdConfig.saveLastShowAd(nextAdSourceTop);
        } else {
            mIvFloatWifiTop.setVisibility(View.GONE);
        }
    }

    private void handleFloatAdClick(AdInfo nextAdSource, AdPositionEnum adPositionEnum) {
        if (nextAdSource.getType() == AdInfo.AD_TYPE_CSJ_FULL_VIDEO) {
            loadFullVideoAd(nextAdSource);
            ReportAgent.reportAdvClick(nextAdSource, ChannelConfig.getChannel(), com.blankj.utilcode.util.AppUtils.getAppVersionCode());
        } else if (nextAdSource.getType() == AdInfo.AD_TYPE_GUANG_DIAN_TONG || nextAdSource.getType() == AdInfo.AD_TYPE_CHUAN_SHAN_JIA) {
            videoAd = new VideoAd(getActivity());
//            videoAd.setOnVideoAdLoadFailedListener(this);
            videoAd.loadVideoAd(nextAdSource);
            ReportAgent.reportAdvClick(nextAdSource, ChannelConfig.getChannel(), com.blankj.utilcode.util.AppUtils.getAppVersionCode());
        } else {
            AdUtils.adClicked(getContext(), nextAdSource, adPositionEnum);
        }
        //showBottomFloat();
    }

    private void loadFullVideoAd(AdInfo posId) {
        if (mFullVideoAd == null) {
            mFullVideoAd = new FullVideoAd();
            mFullVideoAd.setOnFullVideoAdLoadFailedListener(this);
        }
        mFullVideoAd.loadAd(getActivity(), posId);
    }

    private void loadBanner() {
        ivBanner.setVisibility(View.GONE);
        if (!isLoadedBanner) {
            return;
        }
        final AdInfo nextAdSource = mBannerBtmAdConfig.getNextAdSource();
        if (nextAdSource == null) {
            return;
        }
        if (nextAdSource.getType() == AdInfo.AD_TYPE_CHUAN_SHAN_JIA || nextAdSource.getType() == AdInfo.AD_TYPE_GUANG_DIAN_TONG) {
            mFlGdtContainer.setVisibility(View.VISIBLE);
            ivBanner.setVisibility(View.GONE);
            mBannerBtmAdConfig.saveLastShowAd(nextAdSource);
            mBannerAd.loadBannerAdByAdInfo(nextAdSource);
        } else {
//            mBannerBtmAdConfig.saveLastShowLocalAdCode(nextAdSource);
            mBannerBtmAdConfig.saveLastShowAd(nextAdSource);
            ivBanner.setVisibility(View.VISIBLE);
            mFlGdtContainer.setVisibility(View.GONE);
            Glide.with(MeFragment.this)
                    .load(nextAdSource.getIcon())
                    .into(ivBanner);
            ReportAgent.reportAdvExtShow(nextAdSource, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
            ivBanner.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AdUtils.adClicked(getContext(), nextAdSource);
                }
            });
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            showTopFloatAd();
            loadBanner();
            showListAd1();
            showListAd2();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isAdded() && !isHidden()) {
            showTopFloatAd();
            loadBanner();
            showListAd1();
            showListAd2();
        }
        updateGiftState();
    }

    @Override
    public void onFullVideoLoadFailed() {
        if (videoAd == null) {
            videoAd = new VideoAd(getActivity());
        }
        videoAd.loadVideoAd();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onLoadSuccess(AdInfo adSourceAd) {

    }

    @Override
    public void onLoadFail(AdInfo adSourceAd, String errorMsg) {
        mBannerAd.loadBannerAdByAdInfo("945289465");
    }
}
